﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text.RegularExpressions;

namespace MovieCriticsPage.Account
{
    public partial class Register : System.Web.UI.Page
    {
        #region Constans
        public const int MIN_PASSWORD_LENGTH = 6;
        #endregion

        #region Regular Expressions
        public static readonly Regex AccountNameRegex = new Regex(@"\b[A-Z0-9._+-]{4,}\b", RegexOptions.Compiled | RegexOptions.Singleline | RegexOptions.IgnoreCase);

        public static readonly Regex PasswordOnlyLettersAndDigitsRegex = new Regex(@"\b[A-Z0-9]{6,}\b", RegexOptions.Compiled | RegexOptions.Singleline | RegexOptions.IgnoreCase);
        public static readonly Regex PasswordComplicatedRegex = new Regex(@"^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).+$", RegexOptions.Compiled | RegexOptions.Singleline);

        //public static readonly Regex EmaildressRegex = new Regex(@"^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$", RegexOptions.Compiled | RegexOptions.Singleline | RegexOptions.IgnoreCase);
        #endregion

        protected void Page_Load(object sender, EventArgs e)
        {
            //RegisterUser.ContinueDestinationPageUrl = Request.QueryString["ReturnUrl"];
        }

        protected void CreateUserButton_OnClick(object sender, EventArgs e)
        {
            if (Page.IsValid)
            {
                //FormsAuthentication.SetAuthCookie(RegisterUser.UserName, false /* createPersistentCookie */);

                if (RegisterUserInDatabase())
                {
                    // TODO login page with a message that the registration was successful

                    string continueUrl = "~/Account/Login.aspx";
                    Response.Redirect(continueUrl);
                }
            }
        }

        protected bool RegisterUserInDatabase()
        {
            var database = TheApplication.Current.Database;
        
            users new_user = new users();
            new_user.u_userName = this.UserName.Text;
            new_user.u_emailAddress = this.Email.Text;

            try
            {
                database.AddTousers(new_user);
                database.SaveChanges();
            }
            catch { 
                // TODO
                return false;
            }

            return true;
        }

        protected void UniqueUserName_Validator(object source, ServerValidateEventArgs args)
        {
            var database = TheApplication.Current.Database;
            var userName = args.Value;

            if (!AccountNameRegex.IsMatch(userName))
            {
                this.UniqueUserNameValidator.ErrorMessage = "The username has to be at least 4 charachters, containing only letters, digits, -, +, dot and underscore.";
                args.IsValid = false;         
            }
            else if (database.users.Any(user => user.u_userName == userName))
            {
                this.UniqueUserNameValidator.ErrorMessage = "User name is already used by someone else.";
                args.IsValid = false; 
            }
        }

        protected void PasswordComplexity_Validator(object source, ServerValidateEventArgs args)
        {
            string password = args.Value;

            if( password.Length < MIN_PASSWORD_LENGTH )
            {
                this.PasswordComplexityValidator.ErrorMessage = "The password has to be at least " + MIN_PASSWORD_LENGTH + " character.";
                args.IsValid = false;
            }
            else if (!PasswordOnlyLettersAndDigitsRegex.IsMatch(password))
            {
                this.PasswordComplexityValidator.ErrorMessage = "The password can only contain letters and numbers.";
                args.IsValid = false;
            }
            else if (!PasswordComplicatedRegex.IsMatch(password))
            {
                this.PasswordComplexityValidator.ErrorMessage = "The password has to contain at least one lower case, one upper case letter and a digit.";
                args.IsValid = false;
            }    
        }
    }
}
